#-*- coding:utf-8 -*-
import web
import os
print os.name
flag_local=False
if flag_local:
  import sqlite3 as dbm
  
else:
  import MySQLdb as dbm
  from bae.core import const
 
urls = (
    '/save','save',
    '/load','load',
    '/delete','test',
	)
def dbconnect():

  if flag_local:
    dbcon=dbm.connect("D:\\data\\py\\local\\test.db")
  else:
    dbname = "RlJjDChinhImjGwOExZM"
    dbcon=dbm.connect(
            host   = const.MYSQL_HOST,
            port   = int(const.MYSQL_PORT),
            user   = const.MYSQL_USER,
            passwd = const.MYSQL_PASS,
            db     = dbname)

  return dbcon

class save:
  def GET(self):
    args=web.input()
    key=args.get('key')
    content=args.get("content")
    con = dbconnect()
    cur= con.cursor()
    sql='select count(*) from test where time=%s;'%(key);
    cur.execute(sql);
    t=cur.fetchall();
    print t[0][0]
    if t[0][0]>0:
      sql='UPDATE test SET content = %s WHERE time =%s; '%(content,key);
    else:
      sql='insert into test (time,content) values(%s,%s);'%(key,content) 
    print sql
    cur.execute(sql)
    con.commit();
    #cur.execute("select * from test")
    
    #result = cur.fetchall() 

    cur.close()
    con.close()
    return "OK"
class load:
  def GET(self):
    args=web.input()
    key=args.get('key')
    con = dbconnect()
    cur= con.cursor()
    sql='select content from test where time=%s;'%(key);
    cur.execute(sql)
    result = cur.fetchall() 
    cur.close()
    con.close()
    r=""
    if len(result)==0:
      return "NULL"
    else:
      return result[0][0]
 


app = web.application(urls, globals()).wsgifunc()
from bae.core.wsgi import WSGIApplication
application = WSGIApplication(app)
